<template>
  <div>
    <a-row class='mytitle'>
      <span>
        <span class="back-text" @click="handleBack">{{$t('Back')}}</span>
        <span class="split-line">|</span> {{$t('Block')}} / {{$t('Block-detail')}}
      </span>
    </a-row>
    <a-row style="margin:1em;">
      <a-card hoverable>
        <a-row :gutter="16">
          <!-- 基本信息 -->
          <a-col :span="7">
            <a-spin :spinning="infoSpinning">
              <div class="base-card-box" style="height:622px">
              <div class="base-card-title">{{$t('Base_info')}}</div>
              <div class="block-info-content">
                <!-- 块设备ID: -->
                <div class="info-label">{{$t('Block')}} ID:</div>
                <div class="info-value">{{baseInfo && baseInfo.block_id ? baseInfo.block_id : '-'}}</div>
                <!-- 块设备名称 -->
                <div class="info-label">
                  {{$t('Block-name2')}}:
                  <!-- <i class="icon icon-edit16f table-operation-icon" @click="handleEditBlock"></i> -->
                  
                  <Iconfont class="icon table-operation-icon" type="icon-edit16f" @click="handleEditBlock"></Iconfont>
                </div>
                <div class="info-value">{{baseInfo && baseInfo.block_name ? baseInfo.block_name : '-'}}</div>
                <!-- 存储池名称 -->
                <div class="info-label">{{$t('Store-pool-name')}}:</div>
                <div class="info-value">{{baseInfo && baseInfo.pool_name ? baseInfo.pool_name : '-'}}</div>
                <!-- 容量 -->
                <div class="info-label">{{$t('Capacity')}}:</div>
                <div class="info-value">{{baseInfo && baseInfo.size ? baseInfo.size : '-'}}</div>
                <!-- 实际使用量 -->
                <div class="info-label">{{$t('Actual-usage')}}:</div>
                <div class="info-value">{{baseInfo && baseInfo.total_disk_usage ? baseInfo.total_disk_usage : '-'}}</div>
                <!-- 唯一前缀编号 -->
                <div class="info-label">{{$t('Unique-prefix-num')}}:</div>
                <div class="info-value">{{baseInfo && baseInfo.prefix ? baseInfo.prefix : '-'}}</div>
                <!-- 特征 -->
                <div class="info-label">
                  {{$t('Features')}}:
                  <!-- <i class="icon icon-edit16f table-operation-icon" @click="handleEditFeatures"></i> -->
                  
                  <Iconfont class="icon table-operation-icon" type="icon-edit16f" @click="handleEditFeatures"></Iconfont>
                </div>
                <div class="info-value">
                  <template v-if="baseInfo && baseInfo.features_name">
                    <span v-for="(item,index) in baseInfo.features_name" :key="index">
                      {{item}}{{index==baseInfo.features_name.length-1 ? "" : ","}}
                    </span>
                  </template>
                  <!-- {{baseInfo && baseInfo.features_name ? baseInfo.features_name : '-'}} -->
                </div>
                <!-- 快照数量 -->
                <div class="info-label">{{$t('SnapShot-num')}}:</div>
                <div class="info-value">{{baseInfo && baseInfo.snap_count ? baseInfo.snap_count : '-'}}</div>
                <!-- 客户端数量 -->
                <div class="info-label">{{$t('Client-num')}}:</div>
                <div class="info-value">{{baseInfo && baseInfo.iscsi_count ? baseInfo.iscsi_count : '-'}}</div>
              </div>
            </div>
            </a-spin>
          </a-col>
          <!-- 实时事件 -->
          <a-col :span="7">
            <div class="base-card-box" style="height:622px">
              <div class="base-card-title">{{$t('Real-time-info')}}</div>
              <a-row :gutter="25">
                <a-col :span="24">
                  <div class="base-card-table-box">
                    <a-table 
                      :columns="eventColumns"
                      :loading="eventTableLoading" 
                      :dataSource="eventTableData"
                      size="small"
                      :pagination="false"
                      rowKey='client_ip' :locale="defaultSetting"
                      :scroll="eventTableData.length > 9 ? { y: 367 } : {}"
                      :rowClassName="(record, i) => i%2 === 1 ? 'table-even-row' : 'table-odd-row' "
                      bordered
                      style="min-height: 507px"
                    >
                      <template slot="owner" slot-scope="text, record">
                        <!-- <i v-if="record.isLock" class="icon icon-sure64f tick-icon"></i> -->
                        <Iconfont v-if="record.isLock"  class="icon tick-icon" type="icon-sure64f"></Iconfont>
                        <span v-else>-</span>
                      </template>

                      <template slot="lock-title">
                        <span :title="$t('Lock-owner')">{{$t('Lock-owner')}}</span>
                        <a-tooltip>
                          <template slot="title">
                            <span>{{$t('Lock-owner-tip')}}</span>
                          </template>
                          <!-- <i style="color:grey" class="icon a-16_f_ic_about"></i> -->
                          <Iconfont style="color:grey;margin-left: 4px" class="icon" type="a-16_f_ic_about"></Iconfont>
                        </a-tooltip>
                      </template>
                    </a-table>
                  </div>
                </a-col>
                <!-- <a-col :span="15">
                  <div class="base-card-table-box">
                    <div class="real-time-info-box">
                      <p v-for="(item, index) in realTimeEvents" :key="index">{{item}}</p>
                    </div>
                  </div>
                </a-col> -->
              </a-row>
            </div>
          </a-col>
          <!-- 优先级策略信息 -->
          <a-col span="10">
            <a-spin :spinning="infoSpinning">
            <div class="base-card-box" style="height:622px">
              <div class="base-card-title">{{$t('Priority-policy-info')}}</div>
              <a-row :gutter="15">
                <a-col :span="10">
                  <!-- 策略ID -->
                  <div class="info-label">
                    {{$t('Policy-ID')}}: 
                    <!-- <i class="icon icon-edit16f table-operation-icon" @click="handleEditStrategyID"></i> -->

                    <Iconfont class="icon table-operation-icon" type="icon-edit16f" @click="handleEditStrategyID"></Iconfont>
                  </div>
                  <div class="info-value">{{qosData && qosData.strategy_id ? qosData.strategy_id : '-'}}</div>
                </a-col>
                <a-col :span="14">
                  <!-- 策略标识符： -->
                  <div class="info-label" style="height:24px;line-height:24px">{{$t('Policy-identifier')}}：</div>
                  <div class="info-value">{{qosData && qosData.identifier ? qosData.identifier : '-'}}</div>
                </a-col>
              </a-row>
              <div class="base-card-table-box">
                <div v-if="$store.state.language=='zh'" slot="title"><span style="font-weight:700">基本限制</span>（iops单位：次/秒，bps单位：M/s）</div>
                <div v-else slot="title"><span style="font-weight:700">Basic limit</span> (IOPs unit: times / second, BPS unit: m/s)</div>
                <a-table
                  :columns="baseIOPSColumns"
                  :loading="iopsTableLoading" 
                  :dataSource="baseIOPSTableData"
                  size="small"
                  :pagination="false"
                  rowKey='rbd_qos_iops_limit' :locale="defaultSetting"
                  :rowClassName="(record, i) => i%2 === 1 ? 'table-even-row' : 'table-odd-row' "
                  bordered
                >
                </a-table>
              </div>
              <div class="base-card-table-box" style="margin-top:20px">
                <div v-if="$store.state.language=='zh'" slot="title"><span style="font-weight:700">突发限制</span>（iops单位：次/秒，bps单位：M/s）</div>
                <div v-else slot="title"><span style="font-weight:700">Burst Limit</span> (IOPs unit: times / second, BPS unit: m/s)</div>
                <a-table
                  :columns="burstIOPSColumns"
                  :loading="iopsTableLoading" 
                  :dataSource="burstIOPSTableData"
                  size="small"
                  :pagination="false"
                  rowKey='rbd_qos_iops_burst' :locale="defaultSetting"
                  :rowClassName="(record, i) => i%2 === 1 ? 'table-even-row' : 'table-odd-row' "
                  bordered
                >
                </a-table>
              </div>
            </div>
            </a-spin>
          </a-col>
        </a-row>

        <!-- 第二栏 -->
        <a-row :gutter="16" style="margin-top: 16px">
          <!-- 快照信息 -->
          <a-col span="24">
            <a-spin :spinning="infoSpinning">
            <div class="base-card-box">
              <div class="base-card-title">
                {{$t('Snap-info')}}
                <div class="right-btn" @click="handleAddSnap" v-userAuth="'D5-2'">
                  <!-- <i class="icon icon-new16f"></i> -->
                  <Iconfont class="icon" type="icon-new16f"></Iconfont>
                  <span>{{$t('Add-new')}}</span>
                </div>
              </div>
              <div class="base-card-table-box">
                <a-table 
                  :columns="snapColumns"
                  :loading="snapTableLoading" 
                  :dataSource="snapTableData"
                  size="small"
                  :pagination="false"
                  rowKey='snap' :locale="defaultSetting"
                  :scroll="snapTableData.length > 6 ? { y: 250 } : {}"
                  :rowClassName="(record, i) => i%2 === 1 ? 'table-even-row' : 'table-odd-row' "
                  bordered
                  style="min-height: 297px"
                >
                  <!-- 状态 -->
                  <template slot="status" slot-scope="text, record">
                    <span :class="record.is_protected == true ? 'green-circle' : 'red-circle'"></span>
                    <span>{{record.is_protected == true ? $t('Protect') : $t('Unprotect')}}</span>
                  </template>

                  <!-- 创建时间 -->
                  <!-- <template slot="createTime" slot-scope="text, record">
                    <span :title="text.replace(/T/, ' ').replace(/Z/, '')">
                      {{ text ? text.replace(/T/, ' ').replace(/Z/, '') : '-'}}
                    </span>
                  </template> -->

                  <template slot="operate" slot-scope="text, record">
                    <!-- 重命名 -->
                    <a-tooltip placement='top'  v-userAuth="'D5-3'">
                      <template slot='title'>
                        <span>{{$t('Rename')}}</span>
                      </template>
                      <!-- <i
                        class="icon icon-rechristen16f table-operation-icon"
                        @click="handleRename(record)"
                      ></i> -->

                      <Iconfont class="icon table-operation-icon" type="icon-rechristen16f"  @click="handleRename(record)"></Iconfont>
                    </a-tooltip>
                    <!-- 解除保护 -->
                    <a-tooltip placement='top' v-if="record.is_protected"  v-userAuth="'D5-5'">
                      <template slot='title'>
                        <span>{{$t('Remove-protection')}}</span>
                      </template>
                      <!-- <i
                        class="icon icon-unprotect16f table-operation-icon"
                        @click="handleIsProtect(record, 'protect')"
                      ></i> -->
                      <Iconfont class="icon table-operation-icon" type="icon-unprotect16f"  @click="handleIsProtect(record, 'protect')"></Iconfont>
                    </a-tooltip>
                    <!-- 保护 -->
                    <a-tooltip placement='top' v-else  v-userAuth="'D5-4'">
                      <template slot='title'>
                        <span>{{$t('Protect')}}</span>
                      </template>
                      <!-- <i
                        class="icon icon-protect16f table-operation-icon"
                        @click="handleIsProtect(record, 'un-protect')"
                      ></i> -->
                      <Iconfont class="icon table-operation-icon" type="icon-protect16f"  @click="handleIsProtect(record, 'un-protect')"></Iconfont>
                    </a-tooltip>
                    <a-dropdown>
                      <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                        <!-- <i class="icon icon-more16f table-operation-icon"></i> -->
                        <Iconfont class="icon table-operation-icon" type="icon-more16f"></Iconfont>
                      </a>
                      <a-menu slot="overlay">
                        <!-- 克隆 -->
                        <a-menu-item @click="handleCloneSnap(record)" v-userAuth="'D5-6'">
                          <!-- <i class="icon icon-clone16f menu-item-icon"></i> -->

                        <Iconfont class="icon menu-item-icon" type="icon-clone16f"></Iconfont>
                          <span>{{$t('Clone')}}</span>
                        </a-menu-item>
                        <!-- 回滚 -->
                        <a-menu-item @click="handleRollBackSnap(record)" v-userAuth="'D5-7'">
                          <!-- <i class="icon icon-rollbackpart16f menu-item-icon"></i> -->
                        <Iconfont class="icon menu-item-icon" type="icon-rollbackpart16f"></Iconfont>
                          <span>{{$t('Rollback')}}</span>
                        </a-menu-item>
                        <!-- 删除 -->
                        <a-menu-item v-if="!record.is_protected" @click="handleDeleteSnap(record)" v-userAuth="'D5-8'">
                          <!-- <i class="icon icon-delete16f menu-item-icon"></i> -->
                        <Iconfont class="icon menu-item-icon" type="icon-delete16f"></Iconfont>
                          <span>{{$t('Delete')}}</span>
                        </a-menu-item>
                      </a-menu>
                    </a-dropdown>
                  </template>
                </a-table>
              </div>
            </div>
            </a-spin>
          </a-col>
          <!-- 优先级策略信息 -->
          <!-- <a-col span="10">
            <a-spin :spinning="infoSpinning">
            <div class="base-card-box">
              <div class="base-card-title">{{$t('Priority-policy-info')}}</div>
              <a-row :gutter="15">
                <a-col :span="10">
                  策略ID注释
                  <div class="info-label">
                    {{$t('Policy-ID')}}: <i class="icon icon-edit16f table-operation-icon" @click="handleEditStrategyID"></i>
                  </div>
                  <div class="info-value">{{qosData && qosData.strategy_id ? qosData.strategy_id : '-'}}</div>
                </a-col>
                <a-col :span="14">
                  策略标识符：注释
                  <div class="info-label" style="height:24px;line-height:24px">{{$t('Policy-identifier')}}：</div>
                  <div class="info-value">{{qosData && qosData.identifier ? qosData.identifier : '-'}}</div>
                </a-col>
              </a-row>
              <div class="base-card-table-box">
                <div v-if="$store.state.language=='zh'" slot="title"><span style="font-weight:700">基本限制</span>（iops单位：次/秒，bps单位：M/s）</div>
                <div v-else slot="title"><span style="font-weight:700">Basic limit</span> (IOPs unit: times / second, BPS unit: m/s)</div>
                <a-table
                  :columns="baseIOPSColumns"
                  :loading="iopsTableLoading" 
                  :dataSource="baseIOPSTableData"
                  size="small"
                  :pagination="false"
                  rowKey='key' :locale="defaultSetting"
                  :rowClassName="(record, i) => i%2 === 1 ? 'table-even-row' : 'table-odd-row' "
                  bordered
                >
                </a-table>
              </div>
              <div class="base-card-table-box" style="margin-top:20px">
                <div v-if="$store.state.language=='zh'" slot="title"><span style="font-weight:700">突发限制</span>（iops单位：次/秒，bps单位：M/s）</div>
                <div v-else slot="title"><span style="font-weight:700">Burst Limit</span> (IOPs unit: times / second, BPS unit: m/s)</div>
                <a-table
                  :columns="burstIOPSColumns"
                  :loading="iopsTableLoading" 
                  :dataSource="burstIOPSTableData"
                  size="small"
                  :pagination="false"
                  rowKey='key' :locale="defaultSetting"
                  :rowClassName="(record, i) => i%2 === 1 ? 'table-even-row' : 'table-odd-row' "
                  bordered
                >
                </a-table>
              </div>
            </div>
            </a-spin>
          </a-col> -->
        </a-row>
      </a-card>
    </a-row>

    <!-- 编辑块设备名称 -->
    <EditBlock 
      :visible="editBlockNameVisible"
      :targetBlock="targetBlock"
      @closeOperationModal="closeOperationModal"
      @updateInfo="updateInfo"
    />

    <!-- 编辑特征 -->
    <EditFeature 
      :visible="editFeatureVisible"
      :targetBlock="targetBlock"
      @closeOperationModal="closeOperationModal"
      :baseInfo="baseInfo"
      @updateInfo="updateInfo"
    />

    <!-- 新增快照 -->
    <AddSnapshot 
      :visible="addSnapshotVisible"
      :targetBlock="targetBlock"
      @closeOperationModal="closeOperationModal"
      @updateInfo="updateInfo"
    />

    <!-- 重命名快照 -->
    <RenameSnap 
      :visible="renameSnapVisible"
      @closeOperationModal="closeOperationModal"
      :targetBlock="targetBlock"
      :targetSnapshot="targetSnapshot"
      @updateInfo="updateInfo"
    />

    <!-- 删除快照 -->
    <DeleteSnapshot 
      :visible="deleteSnapVisible"
      @closeOperationModal="closeOperationModal"
      :targetSnapshot="targetSnapshot"
      @updateInfo="updateInfo"
    />

    <!-- 编辑策略id -->
    <EditStrategy 
      :visible="editStrategyVisible"
      @closeOperationModal="closeOperationModal"
      :currentPolicyId="currentPolicyId"
      :targetBlock="targetBlock"
      :strategyData="strategyData"
      @updateInfo="updateInfo"
    />

    <!-- 更改保护状态 -->
    <ProtectOrNotSnap 
      :visible="isProtectVisible"
      @closeOperationModal="closeOperationModal"
      :targetSnapshot="targetSnapshot"
      @updateInfo="updateInfo"
    />

    <!-- 快照回滚 -->
    <RollBackSnap 
      :visible="isRollBackVisible"
      :targetSnapshot="targetSnapshot"
      :targetBlock="targetBlock"
      @updateInfo="updateInfo"
      @closeOperationModal="closeOperationModal"
    />

    <!-- 克隆快照 -->
    <CloneSnap 
      :visible="isCloneVisible"
      :targetBlock="targetBlock"
      :targetSnapshot="targetSnapshot"
      @updateInfo="updateInfo"
      @closeOperationModal="closeOperationModal"
    />
  </div>
</template>

<script>
import EditBlock from '@/views/storage_mgr/osd/blockOperation/EditBlock'
import EditFeature from '@/views/storage_mgr/osd/blockOperation/EditFeature'
import EmptyData from '@/components/common/EmptyData'
import AddSnapshot from '@/views/storage_mgr/osd/blockOperation/AddSnapshot'
import RenameSnap from '@/views/storage_mgr/osd/blockOperation/RenameSnap'
import DeleteSnapshot from '@/views/storage_mgr/osd/blockOperation/DeleteSnapshot'
import EditStrategy from '@/views/storage_mgr/osd/blockOperation/EditStrategy'
import ProtectOrNotSnap from '@/views/storage_mgr/osd/blockOperation/ProtectOrNotSnap'
import RollBackSnap from '@/views/storage_mgr/osd/blockOperation/RollBackSnap'
import CloneSnap from '@/views/storage_mgr/osd/blockOperation/CloneSnap'

import { sizeCompare, sortName } from '@/assets/js/tableSortMethods'

export default {
  name: "BlockDetail",
  components: { 
    EditBlock, EditFeature, EmptyData, 
    AddSnapshot, RenameSnap, DeleteSnapshot,
    EditStrategy, ProtectOrNotSnap,
    RollBackSnap, CloneSnap
  },
  data() {
    return {
      editBlockNameVisible: false,
      editFeatureVisible: false,
      addSnapshotVisible: false,
      renameSnapVisible: false,
      deleteSnapVisible: false,
      editStrategyVisible: false,
      isProtectVisible: false,
      isRollBackVisible: false,
      isCloneVisible: false,
      targetBlock: {},
      actions: new Map([
        ['edit-block', () => { this.editBlockNameVisible = false; }],
        ['edit-feature', () => { this.editFeatureVisible = false; }],
        ['add-snap', () => { this.addSnapshotVisible = false; }],
        ['rename-snap', () => { this.renameSnapVisible = false; }],
        ['isProtect-snap', () => { this.isProtectVisible = false; }],
        ['del-snap', () => { this.deleteSnapVisible = false; }],
        ['edit-strategy', () => { this.editStrategyVisible = false; }],
        ['roll-back', () => { this.isRollBackVisible = false; }],
        ['clone-snap', () => { this.isCloneVisible = false; }]
      ]),
      eventTableLoading: false,
      eventColumns: [
        {title: this.$t('Client')+' IP', dataIndex:'client_ip', key:'client_ip', ellipsis: true},
        {slots:{title: 'lock-title'}, dataIndex:'owner', key:'owner', ellipsis: true, scopedSlots:{customRender:'owner'}, width: 140,},
      ],
      eventTableData: [],
      snapTableLoading: false,
      snapColumns: [
        {title: this.$t('Snapshot-name'), dataIndex:'snap', key:'snap', ellipsis: true, sorter: (a, b) => this.sortName(a.snap, b.snap),},
        {title: this.$t('Capacity'), dataIndex:'size', key:'size',  ellipsis: true, sorter: (a, b) => this.sizeCompare(a.size, b.size),},
        {title: this.$t('Status'), dataIndex:'is_protected', key:'is_protected',  ellipsis: true, scopedSlots:{customRender:'status'}, sorter: (a, b) => String(a.is_protected).length - String(b.is_protected).length,},
        {title: this.$t('Create-time'), dataIndex:'timestamp', key:'timestamp', ellipsis: true, scopedSlots:{customRender:'createTime'}, sorter: (a, b) => this.sortTimeFun(a.timestamp, b.timestamp),},
        {title: this.$t('Operate'), width: 120, key:'operate', scopedSlots:{customRender:'operate'}},
      ],
      snapTableData: [],
      iopsTableLoading: false,
      baseIOPSColumns: [
        {title: this.$t('Iops-total'), dataIndex:'rbd_qos_iops_limit', key:'rbd_qos_iops_limit', ellipsis: true},
        {title: this.$t('Iops-read'), dataIndex:'rbd_qos_read_iops_limit', key:'rbd_qos_read_iops_limit', ellipsis: true},
        {title: this.$t('Iops-write'), dataIndex:'rbd_qos_write_iops_limit', key:'rbd_qos_write_iops_limit', ellipsis: true},
        {title: this.$t('Bps-total'), dataIndex:'rbd_qos_bps_limit', key:'rbd_qos_bps_limit', ellipsis: true},
        {title: this.$t('Bps-read'), dataIndex:'rbd_qos_read_bps_limit', key:'rbd_qos_read_bps_limit', ellipsis: true},
        {title: this.$t('Bps-write'), dataIndex:'rbd_qos_write_bps_limit', key:'rbd_qos_write_bps_limit', ellipsis: true},
      ],
      baseIOPSTableData: [
        // {iops_all: '1'}
      ],
      burstIOPSColumns: [
        {title: this.$t('Iops-total'), dataIndex:'rbd_qos_iops_burst', key:'rbd_qos_iops_burst', ellipsis: true},
        {title: this.$t('Iops-read'), dataIndex:'rbd_qos_read_iops_burst', key:'rbd_qos_read_iops_burst', ellipsis: true},
        {title: this.$t('Iops-write'), dataIndex:'rbd_qos_write_iops_burst', key:'rbd_qos_write_iops_burst', ellipsis: true},
        {title: this.$t('Bps-total'), dataIndex:'rbd_qos_bps_burst', key:'rbd_qos_bps_burst', ellipsis: true},
        {title: this.$t('Bps-read'), dataIndex:'rbd_qos_read_bps_burst', key:'rbd_qos_read_bps_burst', ellipsis: true},
        {title: this.$t('Bps-write'), dataIndex:'rbd_qos_write_bps_burst', key:'rbd_qos_write_bps_burst', ellipsis: true},
      ],
      burstIOPSTableData: [
        // {iops_all: '1'}
      ],
      targetSnapshot: {},
      defaultSetting: {emptyText:<EmptyData />},
      currentPolicyId: '',
      infoSpinning: false,
      nowBlockData: {},
      qosData: {},
      strategyData: [],
      realTimeEvents: []
    }
  },
  mounted() {
    this.getTargetBlockInfo();
    this.getStrategy()
  },

  computed: {
    baseInfo() {
      return this.nowBlockData.basic_info
    },
    getlanguage(){
      return this.$store.state.language
    }
  },

  watch:{
    getlanguage(val){ 
      this.eventColumns = [
        {title: this.$t('Client')+' IP', dataIndex:'client_ip', key:'client_ip', ellipsis: true},
        {title: this.$t('Lock-owner'), dataIndex:'owner', key:'owner', ellipsis: true, scopedSlots:{customRender:'owner'},width: 140,},
      ];
      this.snapColumns = [
        {title: this.$t('Snapshot-name'), dataIndex:'snap', key:'snap', ellipsis: true, sorter: (a, b) => this.sortName(a.snap, b.snap),},
        {title: this.$t('Capacity'), dataIndex:'size', key:'size',  ellipsis: true, sorter: (a, b) => this.sizeCompare(a.size, b.size),},
        {title: this.$t('Status'), dataIndex:'is_protected', key:'is_protected',  ellipsis: true, scopedSlots:{customRender:'status'}, sorter: (a, b) => String(a.is_protected).length - String(b.is_protected).length,},
        {title: this.$t('Create-time'), dataIndex:'timestamp', key:'timestamp', ellipsis: true, scopedSlots:{customRender:'createTime'}, sorter: (a, b) => this.sortTimeFun(a.timestamp, b.timestamp),},
        {title: this.$t('Operate'), width: 120, key:'operate', scopedSlots:{customRender:'operate'}},
      ];
      this.baseIOPSColumns = [
        {title: this.$t('Iops-total'), dataIndex:'rbd_qos_iops_limit', key:'rbd_qos_iops_limit', ellipsis: true},
        {title: this.$t('Iops-read'), dataIndex:'rbd_qos_read_iops_limit', key:'rbd_qos_read_iops_limit', ellipsis: true},
        {title: this.$t('Iops-write'), dataIndex:'rbd_qos_write_iops_limit', key:'rbd_qos_write_iops_limit', ellipsis: true},
        {title: this.$t('Bps-total'), dataIndex:'rbd_qos_bps_limit', key:'rbd_qos_bps_limit', ellipsis: true},
        {title: this.$t('Bps-read'), dataIndex:'rbd_qos_read_bps_limit', key:'rbd_qos_read_bps_limit', ellipsis: true},
        {title: this.$t('Bps-write'), dataIndex:'rbd_qos_write_bps_limit', key:'rbd_qos_write_bps_limit', ellipsis: true},
      ];
      this.burstIOPSColumns = [
        {title: this.$t('Iops-total'), dataIndex:'rbd_qos_iops_burst', key:'rbd_qos_iops_burst', ellipsis: true},
        {title: this.$t('Iops-read'), dataIndex:'rbd_qos_read_iops_burst', key:'rbd_qos_read_iops_burst', ellipsis: true},
        {title: this.$t('Iops-write'), dataIndex:'rbd_qos_write_iops_burst', key:'rbd_qos_write_iops_burst', ellipsis: true},
        {title: this.$t('Bps-total'), dataIndex:'rbd_qos_bps_burst', key:'rbd_qos_bps_burst', ellipsis: true},
        {title: this.$t('Bps-read'), dataIndex:'rbd_qos_read_bps_burst', key:'rbd_qos_read_bps_burst', ellipsis: true},
        {title: this.$t('Bps-write'), dataIndex:'rbd_qos_write_bps_burst', key:'rbd_qos_write_bps_burst', ellipsis: true},
      ]
    }
  },

  methods: {
    //获取跳转进来的当前块设备信息
    getTargetBlockInfo() {
      if(this.$route.query.targetBlock) {
        this.targetBlock = JSON.parse(decodeURIComponent(this.$route.query.targetBlock));
        this.getNowBlockInfo(this.targetBlock);
        localStorage.setItem('targetBlock', JSON.stringify(this.targetBlock))
      }
      // else if(localStorage.getItem('targetBlock')) {
      //   this.targetBlock = JSON.parse(localStorage.getItem('targetBlock'));
      //   this.getNowBlockInfo(this.targetBlock);
      // }
      // else if(localStorage.getItem('nowBlockInfo')) {
      //   this.targetBlock = JSON.parse(localStorage.getItem('targetBlock'))
      //   this.nowBlockData = JSON.parse(localStorage.getItem('nowBlockInfo'));
      //   this.snapTableData = this.nowBlockData.snaps_info;
      //   this.qosData = this.nowBlockData.qos_info;
      //   this.handleQosData(this.qosData)
      //   this.infoSpinning = false;
      // }
      // this.initWebSocket()
    },

    // 获取当前块设备的信息
    async getNowBlockInfo(nowBlockInfo) {
      this.infoSpinning = true;
      this.eventTableLoading = true;
      const params = {
        pool_id: nowBlockInfo.pool_id, // 存储池的id号
        image_id: nowBlockInfo.id  // 块设备id号
      };
      const res = await this.$api.blockInfo.getBlockInfoRequest(params);
      console.log('当前块设备的信息：', res)
      this.infoSpinning = false;
      if(res && res.status==200) {
        console.log(res.data)
        this.nowBlockData = res.data;
        this.snapTableData = res.data.snaps_info;
        this.qosData = res.data.qos_info;
        let ipData = res.data.basic_info.ip_address ? res.data.basic_info.ip_address : [];
        let finallyIpData = [];
        const lockAddress = res.data.basic_info.lock_addr;
        ipData.forEach(item => {
          if(lockAddress === item) {
            finallyIpData.push({
              client_ip: item,
              isLock: true
            })
          }else {
            finallyIpData.push({
              client_ip: item,
              isLock: false
            })
          }
        })
        this.eventTableData = finallyIpData;
        if(Object.keys(this.qosData).length !== 0) {
          this.handleQosData(this.qosData)
        }else {
          this.handleQosData({
            rbd_qos_iops_limit: '-',
            rbd_qos_read_iops_limit: '-',
            rbd_qos_write_iops_limit: '-',
            rbd_qos_bps_limit: '-',
            rbd_qos_read_bps_limit: '-',
            rbd_qos_write_bps_limit: '-',
            rbd_qos_iops_burst: '-',
            rbd_qos_read_iops_burst: '-',
            rbd_qos_write_iops_burst: '-',
            rbd_qos_bps_burst: '-',
            rbd_qos_read_bps_burst: '-',
            rbd_qos_write_bps_burst: '-'
          })
        }
        localStorage.setItem('nowBlockInfo', JSON.stringify(res.data));
      }
      this.eventTableLoading = false;
    },

    // 获取策略列表
    async getStrategy() {
      const res = await this.$api.blockInfo.getStrategyRequest()
      if(res && res.data.flag!=1) {
        // console.log('策略列表', res)
        this.strategyData = res.data;
      }
    },

    // 处理qos数据
    handleQosData(data) {
      this.baseIOPSTableData = [];
      this.burstIOPSTableData = [];
      let baseObj = {};
      let burstObj = {};
      for(let key in data) {
        if(key.indexOf('limit') != -1) {
          baseObj[key] = data[key];
        }
        if(key.indexOf('burst') != -1) {
          burstObj[key] = data[key];
        }
      }
      this.baseIOPSTableData.push(baseObj)
      this.burstIOPSTableData.push(burstObj)
    },

    // websocket---start
    initWebSocket() {
      if("WebSocket" in window) {
        const wsUrl = "ws://" + this.wsurl + "/block_op_info";
        this.ws = new WebSocket(wsUrl);
        this.ws.onopen = this.wsOpen;
        this.ws.onmessage = this.wsOnMessage;
        // this.ws.onerror = this.wsOnError;
        this.ws.close = this.wsClose;
      } else {
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
      }
    },
    wsOpen() {
      //打开链接，发送数据
      console.log("websocket已连接，数据发送中...");
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        let params = {
          // rbd:"fw_test",pool:"rbd"
          rbd: this.targetBlock.name,
          pool: this.targetBlock.pool_name,
        }
        this.ws.send(JSON.stringify(params))
        console.log('已发送消息:', JSON.stringify(params));
      } else {
        console.error('WebSocket连接未建立或已关闭');
      }
    },
    wsOnMessage(evt) {
      //接收数据
      let received_msg = JSON.parse(evt.data);
      this.realTimeEvents.push(received_msg.message)
      console.log('接的数据', received_msg)
      // console.log("数据已接收...");
    },
    // wsOnError(event) {
    //   console.log('ws错误', event)
    // },
    wsClose() {
      //关闭连接
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.ws.close();
      } else {
        console.error('WebSocket连接未建立或已关闭');
      }
      // console.log("已断开连接...");
    },

    // websocket---end

    //返回块设备页面
    handleBack() {
      // this.ws.close();
      this.$router.push({
        name: 'block',
        params: { tab: 'block' }
      });
      localStorage.removeItem('nowBlockInfo');
      localStorage.removeItem('targetBlock');
    },

    //编辑块设备名称
    handleEditBlock() {
      this.editBlockNameVisible = true;
    },

    //编辑特征
    handleEditFeatures() {
      this.editFeatureVisible = true;
    },

    //新增快照
    handleAddSnap() {
      this.addSnapshotVisible = true;
    },
    
    //重命名快照
    handleRename(record) {
      this.targetSnapshot = record;
      this.renameSnapVisible = true;
    },

    //编辑策略ID
    handleEditStrategyID() {
      this.editStrategyVisible = true;
    },

    //处理快照是否保护
    handleIsProtect(record, type) {
      this.targetSnapshot = record;
      this.isProtectVisible = true;
    },

    // 快照回滚
    handleRollBackSnap(record) {
      this.targetSnapshot = record;
      this.isRollBackVisible = true;
    },

    // 克隆快照
    handleCloneSnap(record) {
      this.targetSnapshot = record;
      this.isCloneVisible = true;
    },

    //删除快照
    handleDeleteSnap(record) {
      this.targetSnapshot = record;
      this.deleteSnapVisible = true;
    },

    // 获取块设备列表(用来更新当前的this.targetBlock)
    async getBlockList() {
      const res = await this.$api.blockInfo.getBlockListRequest();
      if(res && res.data) {
        res.data.some(item => {
          if(this.targetBlock.id === item.id) {
            this.targetBlock = {...item};
            localStorage.setItem('targetBlock', JSON.stringify(this.targetBlock))
            return true;
          }
        })
      }
    },

    updateInfo() {
      this.getNowBlockInfo(this.targetBlock);
      this.getBlockList();
    },

    //关闭操作弹窗
    closeOperationModal(type) {
      let action = this.actions.get(type);
      action.call(this);
    },

    // 对时间字符串进行排序
    sortTimeFun(a, b) {
      return +new Date(a) - +new Date(b)
    },

    // 容量排序比较
    sizeCompare(a, b) {
      return sizeCompare(a, b)
    },

    // 对名称进行排序
    sortName(a, b) {
      return sortName(a, b)
    }
  },
}
</script>
<style scoped>
  .back-text {
    display: inline-block;
    cursor: pointer;
  }
  .back-text:hover {
    color: var(--themeColor);
  }
  .split-line {
    display: inline-block;
    margin: 0 10px;
  }
  .block-info-content {
    max-height: 438px;
    overflow: auto;
  }
  .info-label {
    font-size: 14px;
    color: #666;
  }
  .info-value {
    font-size: 14px;
    color: #333;
    margin-bottom: 6px;
    font-weight: 700;
  }
  .base-card-box > .info-value:last-child {
    margin-bottom: 0;
  }
  .tick-icon {
    color: var(--mainGreenColor);
  }
  .real-time-info-box {
    border: 1px solid #ededed;
    max-height: 407px;
    min-height: 407px;
    overflow: auto;
    padding: 10px 15px;
  }
  .right-btn {
    float: right;
    cursor: pointer;
  }
  .right-btn > i {
    color: var(--themeColor);
    margin-right: 3px;
  }
  .right-btn > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep.base-card-box .ant-table-body {
    overflow-y: auto !important;
  }
  .menu-item-icon {
    color: var(--themeColor);
    margin-right: 5px;
  }
  ::v-deep.base-card-table-box .ant-table-header {
    /* overflow-y: auto !important; */
  }
</style>